<template>
  <div class="content">
    <dt-search ref="search" :labelWidth="100" :xl="5" :xlBtn="4"></dt-search>
    <Tabs :value="isReceiving" type="card" @on-click="tabClick">
      <TabPane label="承接中" name="2"></TabPane>
      <TabPane label="未承接" name="1"></TabPane>
    </Tabs>
    <div class="handles"></div>
    <dynamic-header
      ref="dynamicHeader"
      @fieldCancel="fieldCancel"
      @headUpdate="headUpdate"
      :sourcedata="sourcedata"
      :targetdata="targetdata"></dynamic-header>
    <dt-grid ref="table" :columns="columns" :page="page" :onFetch="onFetch">
      <div class="flex btn-content pd5" slot="btn">
        <Button type="primary" @click="adjustHeader">调整表头排序</Button>
        <Button type="primary" @click="callRecord" v-if="unlocking('0213020500')">通话记录</Button>
        <Button type="primary" @click="exportData" v-if="unlocking('0213020600')">导出Excel</Button>
      </div>
    </dt-grid>
    <receiver-details ref="detail"></receiver-details>
    <add-receiver ref="addReceiver" @success="dataRefresh" />
  </div>
</template>

<script>
  import dynamicHeader from '@/components/dynamicHeader.vue'
  import addReceiver from './caseReceiverConfig/components/addReceiver.vue'
  import receiverDetails from './components/receiverDetails.vue'
  import columnOpt from './opt/receiverColumn'
  import receiverSearch from './opt/receiverSearch'
  import businessCommonMgr from '@/biz/businessReport/businessCommon'
  import receiverMgr from '@/biz/receiver/receiver'

  export default {
    components: {
      dynamicHeader,
      addReceiver,
      receiverDetails
    },
    data() {
      return {
        leaveUserIds: [],
        paramsAll: {},
        isReceiving: '2',
        tipFlag: true,
        sourcedata: [],
        targetdata: [],
        formValidate: {
          companyIds: [],
          buildingId: '',
          clueGenTime: []
        },
        columns: [],
        page: {
          total: 0,
          current: 1
        },
        leaveCaseFlag: false
      }
    },
    mounted() {
      this.formValidate.buildingId = this.$route.query.buildingId
      this.getColumns()
      this.$refs.table.init(this, new columnOpt(this))
      this.$refs.search.init(this.$refs.table, new receiverSearch(this).options(), this.formValidate)
      console.log(this.$route)
    },
    methods: {
      dataRefresh() {
        setTimeout(() => {
          this.isReceiving = '2'
          this.$refs.table.fetch()
        }, 1000)
      },
      // 列表操作
      delFun(val) {
        receiverMgr.queryOnDeletionLastOne({ buildingId: val.buildingId, userId: val.userId }).then((res) => {
          this.$Modal.confirm({
            title: '删除',
            content: `${
              res
                ? '该顾问为当前案场最后一个电话承接人，删除后将释放该顾问及案场所有呼入号，是否确认要删除'
                : '删除后，该顾问呼入呼出隐私号将被释放，是否确认删除'
            }`,
            onOk: () => {
              receiverMgr.receiverDel({ receiverId: val.id }).then((res) => {
                this.$Message.success('承接人删除成功。')
                setTimeout(() => {
                  this.$refs.table.fetch()
                }, 1000)
              })
            }
          })
        })
      },
      checkFun(val) {
        receiverMgr.usReceiverDetails({ id: val.id }).then((res) => {
          this.$refs.detail.show(res)
        })
      },
      editFun(val) {
        val.value = val.buildingId
        val.label = val.housesName
        this.$refs.addReceiver.show(val)
      },
      // 添加承接人
      addReceiver() {
        this.$refs.addReceiver.show()
      },

      // go通话记录
      callRecord(val) {
        if (val && val.buildingId) {
          this.$router.push({
            path: '/clueManage/caseBusiness/callRecord',
            query: {
              type: 'TOSPUR',
              userId: val.userId,
              buildingId: val.buildingId,
              delFlag: this.isReceiving,
              parentPath: this.$route.query?.parentPath
            }
          })
        } else {
          this.$router.push({
            path: '/clueManage/caseBusiness/callRecord',
            query: {
              type: 'TOSPUR',
              parentPath: this.$route.query?.parentPath
            }
          })
        }
      },
      adjustHeader() {
        this.$refs.dynamicHeader.show()
      },
      //获取表头
      getColumns() {
        businessCommonMgr.reportHeadList({ headType: 8 }).then((res) => {
          this.sourcedata = res.hideHead
          this.targetdata = res.showHead
          this.targetdata.forEach((item, index) => {
            item.disabled = item.fixed
          })
          this.columns = []
          let baseColumns = new columnOpt(this).options()
          this.targetdata.forEach((item) => {
            let column = baseColumns.filter((baseItem) => item.fieldKey == baseItem.field)
            if (column.length) {
              column[0].field = item.fieldKey
              this.columns.push(column[0])
            }
          })
          this.columns.push(baseColumns[baseColumns.length - 1])
          this.$refs.table.fetch()
        })
      },
      // 更新表头
      headUpdate(params) {
        businessCommonMgr.reportHeadUpdate({ headType: 8, updateHead: params.updateInfo }).then((res) => {
          this.getColumns()
          this.$refs.dynamicHeader.hide()
        })
      },
      fieldCancel() {
        this.$refs.dynamicHeader.hide()
      },
      tabClick(val) {
        this.isReceiving = val
        this.$refs.table.fetch(true)
      },
      exportData() {
        receiverMgr.usReceiverExport(this.paramsAll)
      },

      // 列表数据
      onFetch(data, val) {
        console.log(data, 'data')
        this.paramsAll = data
        this.paramsAll.clueGenStartTime = data.clueGenTime[0]
        this.paramsAll.clueGenEndTime = data.clueGenTime[1]
        this.paramsAll.isReceiving = this.isReceiving
        this.paramsAll.channelType = data.channelType != '0' ? data.channelType : ''
        if (this.leaveCaseFlag) {
          this.paramsAll.leaveUserIds = this.leaveUserIds
        } else {
          delete this.paramsAll.leaveUserIds
        }
        return receiverMgr
          .usReceiverList(this.paramsAll)
          .then((res) => {
            this.leaveCaseFlag = false
            this.page.total = res.receiverPage.total
            this.leaveUserIds = res.leaveUserIds
            return res.receiverPage.records
          })
          .catch((err) => {
            this.total = 0
          })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content {
    padding: 20px;
  }
</style>
